package com.ts.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaseFormatUtil {

    public static List<Map<String, Object>> lowerUnderscore(List<Map<String, Object>> list) {
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> map : list) {
            Map<String, Object> retMap = Maps.newHashMap();
            for (Entry<String, Object> entry : map.entrySet()) {
                String mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                //CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, mapKey),
                retMap.put(underlineToCamel(mapKey, true), mapValue);
            }
            ret.add(retMap);
        }
        return ret;
    }

    public static JSONObject lowerUnderscore(JSONObject jsonObj) {
        JSONObject ret = new JSONObject();
        for (Entry<String, Object> entry : jsonObj.entrySet()) {
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            ret.put(underlineToCamel(mapKey, true), mapValue);
        }
        return ret;
    }

    public static Map<String, Object> lowerUnderscore(Map<String, Object> map) {
        Map<String, Object> retMap = Maps.newHashMap();
        for (Entry<String, Object> entry : map.entrySet()) {
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            retMap.put(underlineToCamel(mapKey, true), mapValue);
        }
        return retMap;
    }


    /**
     * 下划线转驼峰法
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underlineToCamel(String line, boolean smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0)) : Character.toUpperCase(word.charAt(0)));
            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index));
            } else {
                sb.append(word.substring(1));
            }
        }
        return sb.toString();
    }

}
